# app.py
from flask_cors import CORS

from flask import Flask, request, jsonify
import os
from werkzeug.utils import secure_filename
from model_runner import run_deepfake_model

app = Flask(__name__)
CORS(app)

UPLOAD_FOLDER = 'upload'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
ALLOWED_EXTENSIONS = {'mp4', 'avi', 'mov'}

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def index():
    return "✅ Flask 后端运行成功，欢迎阳光！"

@app.route('/upload', methods=['POST'])
def upload_video():
    if 'video' not in request.files:
        return jsonify({'error': '没有找到视频文件'}), 400
    
    video = request.files['video']
    filename = secure_filename(video.filename)
    save_path = os.path.join(UPLOAD_FOLDER, filename)
    video.save(save_path)

    # 调用模型识别
    score = run_deepfake_model(os.path.abspath(save_path))
    if score is None:
        return jsonify({'error': '模型识别失败'}), 500
    
    # 将阈值设置为0.25 - 这是根据历史数据分析得出的更合适的阈值
    result = "伪造" if score > 0.25 else "真实"
    print("✅ 最终返回 JSON 数据:", {'score': score, 'result': result})
    return jsonify({'score': score, 'result': result})

if __name__ == '__main__':
    print("Flask服务启动中……")
    app.run(host='0.0.0.0', port=6006)  # 监听6006端口

